package io.github.eric.urpc.standalone.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressionUtil {

    // 压缩字符串
    public static byte[] compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gzipOutputStream.write(str.getBytes("UTF-8"));
        gzipOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    // 解压缩字节数组到字符串
    public static String decompress(byte[] compressedData) throws IOException {
        if (compressedData == null || compressedData.length == 0) {
            return null;
        }
        GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gzipInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        gzipInputStream.close();
        return byteArrayOutputStream.toString("UTF-8");
    }

    public static void main(String[] args) {
        try {
            String originalString = "这是一个待压缩的字符串。This is a sample string to be compressed.";
            System.out.println("Original String: " + originalString);

            // 压缩字符串
            byte[] compressedBytes = compress(originalString);
            System.out.println("Compressed Bytes: " + java.util.Arrays.toString(compressedBytes));

            // 解压缩字符串
            String decompressedString = decompress(compressedBytes);
            System.out.println("Decompressed String: " + decompressedString);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}